module LoginSystem

  protected

  # authenticate_login filter. add
  #
  #   before_filter :authenticate_login
  #
  def authenticate_login
    return true if authenticated_login?
    session[:return_to] = request.request_uri
    access_denied
    return false 
  end

  # overwrite if you want to have special behavior in case the login is not authorized
  # to access the current operation. 
  # the default action is to redirect to the login screen
  # example use :
  # a popup window might just close itself for instance
  def access_denied
    redirect_to :controller => "/login", :action => "login"
  end  

  def redirect_back_or_default(default)
    if session[:return_to].nil?
      redirect_to default
    else
      redirect_to_url session[:return_to]
      session[:return_to] = nil
    end
  end

  def authenticated_login?
    if session[:login_id]
      @current_login = Login.find_by_id(session[:login_id])
      return false if @current_login.nil? 
      return true
    end

    # If not, is the login being authenticated by a token (created by signup/forgot password actions)?
    return false if not params['login']
    id = params['login']['id']
    key = params['key']
    if id and key
      @current_login = Login.authenticate_by_token(id, key)
      session[:login_id] = @current_login ? @current_login.id : nil
      return true if not @current_login.nil?
    end

    # Everything failed
    return false
  end
end
